package com.qf.filter;

import com.qf.util.JwtUtil;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 网关认证过滤器, 鉴权过滤器
 * @author 千锋健哥
 */
@Component
public class AuthFilter implements Ordered, GlobalFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1. 获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        //2. 获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        //3. 获取用户访问的uri地址, 如果是登录路径, 注册路径, 放行
        String uri = request.getURI().getPath();
        if (uri.contains("/auth") || uri.contains("/register")) {
            //放行
            return chain.filter(exchange);
        }
        //4. 从请求头中获取jwt令牌
        String token = request.getHeaders().getFirst("token");
        //5. 判断如果jwt令牌为空, 返回401权限不足状态码
        if (StringUtils.isEmpty(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //返回响应
            return response.setComplete();
        }


        try {
            //6. 解析jwt, 如果解析成功那么请求放行
            JwtUtil.parseJWT(token);
            //放行
            return chain.filter(exchange);
        } catch (Exception e) {
            e.printStackTrace();
            //7. 如果解析有异常, 说明jwt超时或者被篡改, 返回401权限不足状态码
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //返回响应
            return response.setComplete();
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }

}
